import fs from "fs";
import { chalkERROR, chalkINFO, chalkSUCCESS } from "@/utils/chalkTip";
import { logger } from "@/utils/logger";

/**
 * 导出一个函数。
 * 该函数批量以模块方式导入同级目录下的 xxx.router.ts 路由文件
 * 并注册这些路由，放行所有方法
 */

const registerRouter = app => {
    const fileNameArr = fs.readdirSync(__dirname);

    const promises: Promise<any>[] = [];

    for (const fileName of fileNameArr) {
        if (fileName.endsWith(".router.ts") || fileName.endsWith(".router.js")) {
            promises.push(
                new Promise((resolve, reject) => {
                    import("./" + fileName)
                        .then(res => {
                            const router = res.default;
                            app.use(router.routes());
                            app.use(router.allowedMethods());

                            logger.debug(chalkINFO(`加载路由: ${fileName}`));
                            resolve("");
                        })
                        .catch(err => {
                            logger.debug(chalkERROR(`加载路由: ${fileName}出错！`));
                            logger.debug(err);
                            reject(err);
                        });
                })
            );
        }
    }

    Promise.all(promises)
        .then(() => {
            logger.debug(chalkSUCCESS("路由文件加载成功！"));
        })
        .catch(err => {
            logger.debug(chalkERROR("在加载路由文件时出错"));
            logger.debug(err);
        });
};

export { registerRouter };
